<template>
  <div class="orders-section">
    <el-select v-model="params.orderStatus" @change="handleChange" placeholder="全部订单" size="large" style="width: 240px;margin-bottom: 15px;">
      <el-option v-for="item in selectOptions" :key="item.value" :label="item.label" :value="item.value" />
    </el-select>
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="3" animated />
    </div>

    <!-- 空状态 -->
    <el-empty v-else-if="orders.length === 0" description="暂无订单数据" />

    <!-- 订单列表 -->
    <template v-else>
      <div v-for="(order) in orders" :key="order.orderId" class="order-box">
        <div class="order-title">
          <div class="order-info">
            <span>订单时间：{{ formatDate(order.orderCreateTime) }}</span>
            <span>订单状态：{{ order.orderStatus }}</span>
          </div>
          <el-button size="small" type="primary" @click="gotoDetails(order)">查看详情</el-button>
        </div>

        <div class="order-content">
          <div v-for="(item) in order.orderItemList" :key="item.id" class="product-box">
            <img :src="fileBaseUrl() + item.product.imageUrls.split(',')[0]" class="product-img" />
            <div class="product-info">
              <div class="name">{{ item.productName }} / {{ item.product.scenarios }}</div>
              <div class="english">{{ item.product.englishName }}</div>
            </div>
            <div class="product-price">
              <div>单价：¥{{ item.price.toFixed(2) }}</div>
              <div>数量：{{ item.quantity }}</div>
              <div>小计：¥{{ (item.price * item.quantity).toFixed(2) }}</div>
            </div>
          </div>
          <div class="order-total">
            订单总金额：¥{{ calculateOrderTotal(order.orderItemList).toFixed(2) }}
          </div>
        </div>
      </div>
    </template>

  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {fileBaseUrl} from '@/apis/files'
import {getOrderList} from '@/apis/order'

const router = useRouter()
const orderTab = ref('all')
const user = ref(localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")).userInfo : {})
const params = ref({
  orderStatus: '待支付',
  pageNum: 1,
  pageSize: 10,
})
const orders = ref([])
const loading = ref(false)
const selectOptions = [
  {
    value: '待支付',
    label: '待支付',
  },
  {
    value: '已支付',
    label: '已支付',
  },
  {
    value: '已取消',
    label: '已取消',
  },
  {
    value: '全部订单',
    label: '全部订单',
  }
]

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 计算订单总金额
const calculateOrderTotal = (orderItems) => {
  return orderItems.reduce((total, item) => {
    return total + (item.price * item.quantity)
  }, 0)
}

const handleChange=()=>{
  findOrders()
}

const findOrders = async () => {
  loading.value = true
  try {
    const res = await getOrderList(params.value)
    if (res.code === '0') {
      orders.value = res.data.records
      if (orders.value.length === 0) {
        ElMessage.info('暂无订单数据')
      }
    } else {
      ElMessage.error(res.msg || '获取订单数据失败')
      orders.value = []
    }
  } catch (err) {
    ElMessage.error('获取订单数据失败')
    orders.value = []
  } finally {
    loading.value = false
  }
}

const gotoDetails = (order) => {
  if (!order || !order.orderId) {
    ElMessage.error('订单信息不完整')
    return
  }
  router.push({
    name: 'OrderDetail',
    params: {
      id: order.orderId
    }
  })
}

onMounted(() => {
  
  findOrders()
})
</script>

<style scoped>
.orders-section {
  padding: 20px;
  min-height: calc(100vh - 55px);
}

.loading-container {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
}

.order-box {
  margin-bottom: 20px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background: #fff;
}

.order-title {
  padding: 15px;
  background: #f5f7fa;
  border-bottom: 1px solid #ddd;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.order-info {
  display: flex;
  gap: 20px;
}

.order-info span {
  font-size: 14px;
  color: #606266;
}

.order-content {
  padding: 15px;
}

.product-box {
  display: flex;
  padding: 15px 0;
  border-bottom: 1px solid #eee;
  align-items: center;
}

.product-box:last-child {
  border-bottom: none;
}

.product-img {
  width: 80px;
  height: 80px;
  object-fit: cover;
  margin-right: 15px;
  border-radius: 4px;
}

.product-info {
  flex: 1;
  padding-right: 20px;
  min-width: 0;
}

.name {
  font-size: 14px;
  margin-bottom: 5px;
  color: #303133;
  word-break: break-all;
}

.english {
  color: #666;
  font-size: 13px;
}

.product-price {
  width: 200px;
  text-align: right;
  flex-shrink: 0;
}

.product-price>div {
  margin-bottom: 5px;
  color: #606266;
}

.order-total {
  text-align: right;
  padding: 15px 0;
  font-size: 16px;
  font-weight: bold;
  color: #f56c6c;
  border-top: 1px solid #eee;
  margin-top: 10px;
}
</style>